package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.CartItem;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class UpdateCartQuantitiesServlet extends HttpServlet {

    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private String updateQuantity = null;
    private Cart cart;


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Account account = (Account)session.getAttribute("account");
        AccountService accountService = new AccountService();


        cart = (Cart)session.getAttribute("cart");
        List<CartItem> cartItemList = cart.getCartItemList();

        for (int i = 0; i < cartItemList.size(); i++) {
            String itemId = cartItemList.get(i).getItem().getItemId();
            updateQuantity = req.getParameter(itemId);

            if(updateQuantity != null){
                cartItemList.get(i).setQuantity((Integer.parseInt(updateQuantity)));

                accountService.updateCartByAccount(account,itemId,Integer.parseInt(updateQuantity));
            }

        }

        session.setAttribute("cart",cart);



        if(account != null){
            HttpServletRequest httpRequest= req;
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

            LogService logService = new LogService();

            String logInfo = logService.logInfo(" ") + strBackUrl + " 更新购物车内容";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }

        req.getRequestDispatcher(VIEW_CART).forward(req,resp);

    }


}
